package com.spzx.product.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.product.service.ProductService;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class ProductReceiver {

    @Autowired
    private ProductService productService;

    //还原库存（解锁库存）
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_UNLOCK, durable = "true"),
            key = {MqConst.ROUTING_UNLOCK}
    ))
    public void unlock(String orderNo,Message message,Channel channel) {
        if(!StringUtils.isEmpty(orderNo)) {
            //调用service方法实现还原库存
            productService.unLockProductStock(orderNo);
        }
        //手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


    //扣减库存
    /**
     * 扣减库存
     * @param orderNo  订单号
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_MINUS, durable = "true"),
            key = {MqConst.ROUTING_MINUS}
    ))
    public void minus(String orderNo, Channel channel, Message message) {
        //业务处理
        if (StringUtils.hasText(orderNo)){
            //扣减库存
            productService.minusStock(orderNo);
        }

        //手动应答
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
